package com.nineclock.message.service.impl;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.service.PushRecordService;
import com.nineclock.system.pojo.NcMessage;
import com.nineclock.system.pojo.NcMessageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class PushRecordServiceImpl implements PushRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<NcMessage> message(NcMessageDTO dto) {

        if (dto.getTargetId() == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        List<NcMessage> ncMessages = mongoTemplate.find(Query.query(
                Criteria.where("approveUserId").is(dto.getTargetId()).and("messageType").is(dto.getType()))
                .with(Sort.by(Sort.Direction.ASC, "approveStatue")), NcMessage.class);
        if (ncMessages == null || ncMessages.size()==0) {

            List<NcMessage> ncMessageList = mongoTemplate.find(Query.query(Criteria.where("applyUserId")
                    .is(dto.getTargetId()).and("messageType").is(dto.getType())).with(Sort.by(Sort.Direction.ASC, "approveStatue")), NcMessage.class);
            return ncMessageList;
        }
        return ncMessages;

    }
}
